<template>
  <div class="basketball-container">
    <div class="basketball-header">
      <img class="left" @click="$router.go(-1)" src="../../../assets/imgs/icon-back@2x.png" alt>
      <img
        class="right"
        @click="showTip=true"
        src="../../../assets/imgs/live/touzhu_icon_gengduo.png"
        alt
      >
      <div class="center" @click="showSelectType=true">
        {{matchTypes[tabIndex].label}}
        <img
          src="../../../assets/imgs/live/touzhu_icon_xiala.png"
          alt
        >
      </div>
    </div>
    <div class="basketball-content mtop">
      <component
        :is="currentView[tabIndex]"
        @selectMatch="selectMatch"
        @selectBatchMatch="selectBatchMatch"
        @selectAllBatchMatch="selectAllBatchMatch"
        :selectedMatchs="selectedMatchs"
        :matchList="matchList"
      ></component>
    </div>
    <div class="basketball-footer">
      <div class="clear-btn" @click="clearMatch">清空</div>
      <div class="select-tip">
        <div>
          <div class="top">已选择{{getCount()}}场</div>
          <div class="bottom">至少选择2场比赛</div>
        </div>
      </div>
      <div class="go-buy" @click="goBuy">选好了</div>
    </div>
    <div v- class="select-type-modal">
      <x-dialog v-model="showSelectType" hide-on-blur :dialog-style="{'display': 'block', 'max-width': 'unset', 'width': '100%', 'height': '1.2rem',
      'top': 0, 'left': 0, 'right': 0, 'margin': 0}">
        <div class="modal-content">
          <div
            :key="index"
            v-for="(item, index) in matchTypes"
            @click="selectType(index)"
          >{{item.label}}</div>
        </div>
      </x-dialog>
    </div>
    <div v- class="show-tip-modal">
      <x-dialog v-model="showTip" hide-on-blur :dialog-style="{'display': 'block', 'width': '2rem', 'height': '1.2rem',
      'top': '0.8rem', 'left': 'auto', 'right': 0, 'margin': 0}">
        <div class="modal-content">
          <div class="top" @click="startFilter">赛事筛选</div>
          <div>玩法介绍</div>
        </div>
      </x-dialog>
    </div>
    <confirm
      v-if="showSelectModeModal"
      v-model="showSelectModeModal"
      title="赛事筛选"
      @on-cancel="showSelectModeModal=false"
      @on-confirm="confirmSelectModal"
    >
      <div class="modal-tab-wrapper">
        <span
          :key="index"
          @click.stop="onModalTabChange(tab.key)"
          v-for="(tab, index) in allTabs"
          :class="tab.key===copyMode?'active-tab':''"
        >{{tab.value}}</span>
      </div>
      <div class="modal-matchmode-wrapper">
        <span
          :key="index"
          @click.stop="onmatchmodeSelect(matchmode.key)"
          v-for="(matchmode, index) in allmatchmodes"
          :class="copymatchmode[matchmode.key]?'active-matchmode':''"
        >{{matchmode.value}}</span>
      </div>
    </confirm>
    <div v-transfer-dom>
      <loading :show="showData" text="数据加载中"></loading>
    </div>
  </div>
</template>
<script>
import { mapActions } from 'vuex';
import MixMatch from './MixMatch';
import SF from './SF';
import RFSF from './RFSF';
import SFC from './SFC';
import DXF from './DXF';
import { XDialog, Confirm, Loading } from 'vux';
import cloneDeep from 'lodash/cloneDeep';
import values from 'lodash/values';
import keys from 'lodash/keys';
export default {
  components: {
    XDialog,
    Confirm,
    Loading
  },
  data () {
    return {
      // Score -> 胜分差
      showData: false,
      currentView: [MixMatch, SF, RFSF, SFC, DXF],
      matchTypes: [
        {
          value: '0',
          label: '混合过关'
        },
        {
          value: '1',
          label: '胜负'
        },
        {
          value: '2',
          label: '让分胜负'
        },
        {
          value: '3',
          label: '胜分差'
        },
        {
          value: '4',
          label: '大小分'
        }
      ],
      tabIndex: 0,
      showSelectType: false,
      showTip: false,
      matchList: [],
      selectedMatchs: {},
      showSelectModeModal: false,
      allTabs: [{ key: '0', value: '全部' }, { key: '1', value: '反选' }],
      selectedTab: '',
      allmatchmodes: [],
      selectedmatchmodes: {},
      copymatchmode: {},
      copyMode: ''
    };
  },
  mounted () {
    localStorage.removeItem('payCache');
    const matchCacheObj = localStorage.getItem('matchCache');
    if (matchCacheObj) {
      const {
        selectedTab,
        tabIndex,
        matchList,
        selectedMatchs,
        allmatchmodes,
        selectedmatchmodes
      } = JSON.parse(matchCacheObj);
      this.selectedTab = selectedTab;
      this.tabIndex = tabIndex;
      this.matchList = matchList;
      this.selectedMatchs = selectedMatchs;
      this.allmatchmodes = allmatchmodes;
      this.selectedmatchmodes = selectedmatchmodes;
    } else {
      this.fetchData();
      const body = {
        type: 2
      };
      this.getRatioLeagueList(body).then(res => {
        if (res) {
          this.allmatchmodes = res.league_list.map(
            ({ nm_league_id: key, short_name_zh: value }) => ({ key, value })
          );
        }
      });
    }
  },
  methods: {
    ...mapActions({
      getRatioLeagueList: 'match/getRatioLeagueList',
      getRatioListLQ: 'match/getRatioListLQ'
    }),
    fetchData () {
      const nm_league_ids = Object.keys(this.selectedmatchmodes).filter(s => this.selectedmatchmodes[s])
        .join(','); ;

      this.showData = true;
      this.getRatioListLQ({ nm_league_ids }).then(res => {
        if (res) {
          this.matchList = res.date_list.map(({...t}) => ({...t, showDetail: true}));
        }
        this.showData = false;
      });
    },
    handleTabClick (index) {
      this.tabIndex = index;
      this.$router.replace({ name: 'Basketball', query: { type: index } });
    },
    selectType (index) {
      this.tabIndex = index;
      this.showSelectType = false;
    },
    selectMatch ({ nm_matches_id, type, issue_num, i, value }) {
      if (!this.selectedMatchs[nm_matches_id]) {
        this.selectedMatchs[nm_matches_id] = {};
      }
      if (!this.selectedMatchs[nm_matches_id][issue_num]) {
        this.selectedMatchs[nm_matches_id][issue_num] = {};
      }
      if (!this.selectedMatchs[nm_matches_id][issue_num][type]) {
        this.selectedMatchs[nm_matches_id][issue_num][type] = {};
      }

      const typeObj = this.selectedMatchs[nm_matches_id][issue_num][type];
      if (typeObj[i]) {
        delete typeObj[i];
      } else {
        typeObj[i] = value;
      }
      this.selectedMatchs = cloneDeep(this.selectedMatchs);
    },
    selectBatchMatch ({ nm_matches_id, type, issue_num, data }) {
      if (!this.selectedMatchs[nm_matches_id]) {
        this.selectedMatchs[nm_matches_id] = {};
      }
      if (!this.selectedMatchs[nm_matches_id][issue_num]) {
        this.selectedMatchs[nm_matches_id][issue_num] = {};
      }
      this.selectedMatchs[nm_matches_id][issue_num][type] = data;
      this.selectedMatchs = cloneDeep(this.selectedMatchs);
    },
    selectAllBatchMatch ({ nm_matches_id, issue_num, data }) {
      if (!this.selectedMatchs[nm_matches_id]) {
        this.selectedMatchs[nm_matches_id] = {};
      }
      if (!this.selectedMatchs[nm_matches_id][issue_num]) {
        this.selectedMatchs[nm_matches_id][issue_num] = {};
      }
      const orgData = this.selectedMatchs[nm_matches_id][issue_num];
      // 兼容胜分差
      this.selectedMatchs[nm_matches_id][issue_num] = {...orgData, ...data};
      this.selectedMatchs = cloneDeep(this.selectedMatchs);
    },
    clearMatch () {
      this.selectedMatchs = {};
    },
    getCount () {
      return values(this.selectedMatchs)
        .map(s => values(s)[0])
        .filter(s => {
          return (
            keys(s.sf).length !== 0 ||
            keys(s.rf).length !== 0 ||
            keys(s.zs).length !== 0 ||
            keys(s.ks).length !== 0 ||
            keys(s.dxf).length !== 0
          );
        }).length;
      // return Object.keys(this.selectedMatchs).length;
    },
    goBuy () {
      const count = this.getCount();
      if (count < 2) {
        this.$vux.toast.text('至少选择2场比赛');
        return;
      }

      // get the ids of the selected matchs
      const selectMatchIds = keys(this.selectedMatchs).filter(s => {
        const ss = values(this.selectedMatchs[s])[0];
        return (
          keys(ss.sf).length !== 0 ||
          keys(ss.rf).length !== 0 ||
          keys(ss.zs).length !== 0 ||
          keys(ss.ks).length !== 0 ||
          keys(ss.dxf).length !== 0
        );
      })
      console.log(this.selectedMatchs, 56789, selectMatchIds)
      const matchList = this.matchList.reduce((t, c) => {
        const mm = c.matches_list.filter(m =>
          selectMatchIds.includes(m.nm_matches_id)
        );
        t = t.concat(mm);
        return t;
      }, []);

      localStorage.setItem(
        'matchCache',
        JSON.stringify({
          matchList: this.matchList,
          selectedMatchs: this.selectedMatchs,
          selectedTab: this.selectedTab,
          tabIndex: this.tabIndex,
          allmatchmodes: this.allmatchmodes,
          selectedmatchmodes: this.selectedmatchmodes
        })
      );

      this.$router.push({
        name: 'BasketballPay',
        params: { matchList, selectedMatchs: this.selectedMatchs, tabIndex: this.tabIndex }
      });
    },
    startFilter () {
      this.showTip = false;
      this.showSelectModeModal = true;
    },
    onModalTabChange (key) {
      this.copyMode = key;
      this.allmatchmodes.forEach(s => {
        if (key === '0') {
          this.copymatchmode[s.key] = true;
        } else if (key === '1') {
          this.copymatchmode[s.key] = !this.copymatchmode[s.key];
        }
      });
      this.$forceUpdate();
    },
    onmatchmodeSelect (key) {
      const value = !!this.copymatchmode[key];
      this.copymatchmode[key] = !value;
      this.$forceUpdate();
    },
    openSelectModal () {
      this.showSelectModeModal = true;
      this.copymatchmode = { ...this.selectedmatchmodes };
      this.copyMode = this.selectedTab;
    },
    confirmSelectModal () {
      this.selectedmatchmodes = { ...this.copymatchmode };
      this.showSelectModeModal = false;
      this.selectedTab = this.copyMode;
      this.fetchData();
    }
  }
};
</script>
<style lang="less">
.basketball-container {
  .basketball-header {
    position: fixed;
    background: #d44743;
    height: 0.8rem;
    color: #ffffff;
    top: 0;
    width: 100%;
    display: flex;
    justify-content: center;
    z-index: 10;
    .left {
      position: absolute;
      left: 0.2rem;
      width: 0.23rem;
      height: 0.4rem;
      top: 0.2rem;
    }
    .right {
      position: absolute;
      right: 0.2rem;
      top: 0.24rem;
      height: 0.29rem;
      width: 0.4rem;
    }
    .center {
      text-align: center;
      width: 3.2rem;
      line-height: 0.8rem;
      img {
        height: 0.16rem;
        width: 0.24rem;
      }
    }
  }
  .basketball-content {
    padding-bottom: 0.8rem;
  }
  .basketball-footer {
    position: fixed;
    bottom: 0;
    height: 0.97rem;
    right: 0;
    left: 0;
    display: flex;
    justify-content: space-between;
    background: #ffffff;
    border-top: 1px solid #eeeeee;
    .clear-btn {
      border-right: 1px solid #eeeeee;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 1.4rem;
      color: #202020;
      font-size: 0.26rem;
      height: 0.97rem;
      justify-content: center;
      align-items: center;
    }
    .select-tip {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 3.5rem;
      color: #202020;
      font-size: 0.22rem;
      height: 0.97rem;
      text-align: center;
      .top {
        color: #d44743;
        margin-bottom: 0.08rem;
      }
    }
    .go-buy {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 2.6rem;
      background: #d44743;
      color: #ffffff;
      font-size: 0.34rem;
      height: 0.97rem;
    }
  }
  .select-type-modal {
    .modal-content {
      // position: fixed;
      // top: 0;
      // left: 0;
      // right: 0;
      background: #ffffff;
      font-size: 0.24rem;
      color: #202020;
      text-align: left;
      div {
        width: 33%;
        display: inline-block;
        text-align: center;
        height: 0.6rem;
        line-height: 0.6rem;
      }
    }
  }
  .show-tip-modal {
    .modal-content {
      // width: 2rem;
      // position: fixed;
      // top: 0.8rem;
      // right: 0;
      background: #ffffff;
      font-size: 0.24rem;
      color: #202020;
      div {
        height: 0.6rem;
        line-height: 0.6rem;
        &.top {
          border-bottom: 1px solid #eeeeee;
        }
      }
    }
  }
  .modal-tab-wrapper {
    display: flex;
    margin-bottom: 0.2rem;
    // display: flex;
    justify-content: center;
    span {
      color: #747474;
      font-size: 0.26rem;
      width: 33.3%;
      padding: 0.12rem 0;
      border-top: 1px solid #d2d2d2;
      border-bottom: 1px solid #d2d2d2;
      border-left: 1px solid #d2d2d2;
      &.active-tab {
        background: #d44743;
        color: #fff;
      }
      &:nth-child(1) {
        border-top-left-radius: 0.1rem;
        border-bottom-left-radius: 0.1rem;
      }
      &:nth-child(2) {
        border-right: 1px solid #d2d2d2;
        border-top-right-radius: 0.1rem;
        border-bottom-right-radius: 0.1rem;
      }
    }
  }
  .modal-matchmode-wrapper {
    text-align: left;
    span {
      display: inline-block;
      text-align: center;
      color: #747474;
      font-size: 0.26rem;
      width: 30%;
      padding: 0.12rem 0;
      border: 1px solid #d2d2d2;
      margin-bottom: 0.1rem;
      border-radius: 0.1rem;
      &.active-matchmode {
        color: #d44743;
        border: 1px solid #d44743;
      }
      &:nth-child(3n + 2) {
        margin-left: 3%;
        margin-right: 3%;
      }
    }
  }
}
</style>
